// components/title2/title2.js
var timeUtil = require('../../utils/timeUtils')
var handler = require('../../utils/dataHander')
var util = require("../../utils/pageChangeUtils")
var app = getApp()
Component({
  options: {
    styleIsolation: "apply-shared"
  },
  /**
   * 组件的属性列表
   */
  properties: {

  },

  observers: {
    "index": function (index) {
      this.triggerEvent("fuZiTongXin", index)
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    items: [], //题目
    tishu: 0,
    index: 0,
    answers: [], //选中的答案
    item: [],
    bc_default: '#FBFBFB',
    bc_select: '#CAE1FF',
    bcA: '',
    bcB: '',
    bcC: '',
    bcD: '',
    bcE: '',
    array: [],
    beginTime: 0,
    answersList: [], //正确答案
    setInter: 0,
    percent: 0,
    residueTime: "",
    testTime: 0, //允许用来考试的时间
    radio: true,
    selectedArr: []
  },

  /**
   * 组件的方法列表
   */
  methods: {
    _setQuestion: function (e) {
      var that = this;
      var ind = that.data.index;
      //先把原来内容请空
      this.setData({
        item: [],
        radio: that.data.items[ind].answer.length > 1 ? false : true,
      })
      setTimeout(function () {
        that.setData({
          item: that.data.items[ind],
        }, 50)
      })
      var ans = that.data.answers[that.data.index];
      var r = ans.filter(function (s) {
        return s && s.trim()
      })
      this._selectItemChange(r)
    },
    /**
     * 在这里把对应题的颜色和选项改变
     * @param {*} e 
     */
    _selectItemChange: function (e) {
      var that = this
      this.setData({
        bcA: that.data.bc_default,
        bcB: that.data.bc_default,
        bcC: that.data.bc_default,
        bcD: that.data.bc_default,
      })
      for (let i = 0; i < e.length; i++) {
        if (e[i] == 'A') {
          this.setData({
            bcA: that.data.bc_select,
          })
        }
        if (e[i] == 'B') {
          this.setData({
            bcB: that.data.bc_select,
          })
        }
        if (e[i] == 'C') {
          this.setData({
            bcC: that.data.bc_select,
          })
        }
        if (e[i] == 'D') {
          this.setData({
            bcD: that.data.bc_select,
          })
        }
      }
    },

    btnOpClick: function (e) {
      var selectedArr = this.data.selectedArr
      selectedArr.push(this.data.index)
      //将选中的答案放到一个数组中
      var select = e.detail.value
      var arr = new Array(4)
      arr.fill("")
      var that = this
      that.setData({
        bcA: that.data.bc_default,
        bcB: that.data.bc_default,
        bcC: that.data.bc_default,
        bcD: that.data.bc_default,
      })
      for (let i = 0; i < select.length; i++) {
        if (select[i] == "A") {
          arr[0] = "A"
          that.setData({
            bcA: that.data.bc_select,
          })
        }
        if (select[i] == "B") {
          arr[1] = "B"
          that.setData({
            bcB: that.data.bc_select,
          })
        }
        if (select[i] == "C") {
          arr[2] = "C"
          that.setData({
            bcC: that.data.bc_select,
          })
        }
        if (select[i] == "D") {
          arr[3] = "D"
          that.setData({
            bcD: that.data.bc_select,
          })
        }
      }
      //拿到填写答案的数组集合
      //后续需要在这里把arr数据保存起来
      var myAnswer = that.data.answers
      myAnswer[that.data.index] = arr
      //将用户选择的选项保存到data里
      that.setData({
        answers: myAnswer
      })
    },

    _bindPickerChange: function (e) {
      this.setData({
        index: parseInt(e)
      })
      this._setQuestion();
    },

    _nextQuestion: function () {
      var that = this
      //只要不是最后一道题，就做下一题
      if (this.data.index < that.data.tishu - 1) {
        that.setData({
          index: this.data.index + 1
        });
        that._setQuestion();
      }
    },
    _lastQuestion: function () {
      //这里回到上一题时需要显示出之前的答案
      var that = this;
      //只要不是第一道题，就做
      if (this.data.index > 0) {
        this.setData({
          index: this.data.index - 1
        });
        that._setQuestion();
      }
    },

    _showResult: function () {
      app.globalData.time = new Date().getTime() - this.data.beginTime;
      var that = this
      //找出错题，并算出得分
      var subject = this.data.items
      var correctAnswer = this.data.answersList
      var myAnswers = this.data.answers
      handler.score(subject, myAnswers, correctAnswer).then(res => {
        wx.navigateTo({
          url: '../../results/results/result',
        })
      })
    },

    _submit: function (submit) {
      var that = this
      //找出选中的答案选项
      var selectAnswer = this.data.answers
      handler.findUnselect(selectAnswer).then(res => {
        //这里表示题目都做完了
        if (submit.confirm) { //如果没有题目做了标记，直接显示正确答案
          this._showResult()
        } else { //如果题目做了标记，给用户提示
          wx.showModal({
            title: "提示框",
            content: "标记的题目不再看看吗？",
            cancelText: "检查一下",
            confirmText: "直接交卷",
            success: function (e) {
              if (e.confirm) {
                console.log("confirm", that.data)
                that._showResult()
              } else {
                that.setData({
                  index: submit.flagArr
                })
                that._setQuestion()
              }
            }
          })
        }
      }).catch(err => {
        //这里表明有题目没做完
        if (this.data.percent != 100) {
          handler.compareNoOne(this.data.selectedArr, this.data.tishu).then(response => {
            wx.showModal({
              title: "提示框",
              content: "还有题目没有做完，不检查一下吗(●'◡'●)ﾉ♥",
              cancelText: "检查一下",
              confirmText: "直接交卷",
              success(res) {
                if (res.confirm) {
                  that._showResult()
                } else {
                  that.setData({
                    index: response[0]
                  })
                  that._setQuestion()
                }
              }
            })
          })
        }
        //否则时间到，自动交卷
        else {
          this._showResult()
        }
      })
    },

  },
  lifetimes: {
    attached: function () {
      var that = this
      var subject = wx.getStorageSync('subject')
      var topSubject = app.globalData.selectLib
      //从数据库中查出考试题目和考试时间
      // 从已经打乱的题库中选题目
      let testItem = wx.getStorageSync('testItem')
      util.findTestItem(topSubject, testItem).then(res => {
        var testSubject = subject.slice(0, res.items)
        var len = testSubject.length
        var answers = new Array(len);
        for (let i = 0; i < answers.length; i++) {
          var answerArr = new Array(4)
          answers[i] = answerArr
          for (let p = 0; p < answerArr.length; p++) {
            answers[i][p] = ""
          }
        }
        var arr = new Array(len)
        var answersList = new Array(0);
        for (var i = 0; i < len; i++) {
          arr[i] = testSubject[i].question.substring(0, 22);
        }
        //把所有正确的答案都找出来
        for (let i = 0; i < testSubject.length; i++) {
          var element = testSubject[i].answer;
          answersList.push(element)
        }
        this.setData({
          items: testSubject,
          tishu: len,
          answers: answers,
          answersList: answersList,
          array: arr,
          beginTime: new Date().getTime(),
          testTime: res.time
        });
        this._setQuestion();
        //页面渲染完开始计算时间
        var t1 = 1;
        var that = this
        var testTime = that.data.testTime
        that.data.setInter = setInterval(function () {
          t1++
          var done = t1 / testTime
          that.setData({
            percent: done * 100,
            residueTime: timeUtil.formatTime(testTime - t1)
          })
          if (done === 1) {
            //时间到自动交题
            clearInterval(that.data.setInter)
            that.submit()
          }
        }, 1000)
      })
    },
    detached: function () {
      clearInterval(this.data.setInter)
    }
  }
})